from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, ListModelMixin, DestroyModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from community.models import Article, Comment
from utils.permission import create_user_auto, update_user_auto, destroy_user_auto
from .serializers import ArticleSerializer, CommentSerializer, CommentDetailSerializer


class ArticlePaginationPageNumber(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    max_page_size = 100


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False, status=1)
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = ArticlePaginationPageNumber

    @create_user_auto
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @update_user_auto(Article)
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @destroy_user_auto(Article)
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        # 这里要用filter 因为update是修改查询集 把一个字段的数据查询出来用F查询
        Article.objects.filter(id=kwargs['pk']).update(page_view=F('page_view') + 1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=['get'], detail=True)
    def comment(self, request, pk):  # 查询指定文章的所有评论
        comment = Comment.objects.filter(level=1, article=pk)
        serializer = CommentDetailSerializer(comment, many=True)
        return Response(serializer.data)


class CommentViewSet(GenericViewSet, CreateModelMixin, ListModelMixin, DestroyModelMixin):
    queryset = Comment.objects.filter(level=1)
    serializer_class = CommentDetailSerializer
    permission_classes = [IsAuthenticated]

    @create_user_auto
    def create(self, request, *args, **kwargs):
        return CreateModelMixin.create(self, request, *args, **kwargs)

    @destroy_user_auto(Comment)
    def destroy(self, request, *args, **kwargs):
        return DestroyModelMixin.destroy(self, request, *args, **kwargs)
